package wsp.dailymarket.partners;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;
import javax.sql.DataSource;
import wsp.dailymarket.auth.AuthenticationBean;
import wsp.dailymarket.obj.UserProfileBean;

/**
 * Viewing and making changes to a Partner's Company Profile
 * @author Matt
 */
@ManagedBean(name = "partnerCompanyProfileBean")
@RequestScoped
public class PartnerCompanyProfileBean {

	@Resource(name = "jdbc/dmderby")
	private DataSource ds;
	@ManagedProperty(value = "#{authenticationBean}")
	private AuthenticationBean authBean;
	private PartnerProfile currentProfile;

	public PartnerCompanyProfileBean() {
		currentProfile = new PartnerProfile();
	}

	public void fetchCompanyProfile() throws SQLException {
		if (this.currentProfile == null) {
			this.currentProfile = new PartnerProfile();
		}

		if (this.currentProfile.getCompanyId() == null || "".equals(this.currentProfile.getCompanyId())) {
			if (this.authBean.getAuthentication().getClientType() == UserProfileBean.CLIENT_TYPE_PARTNER) {
				this.currentProfile.setCompanyId(this.authBean.getAuthentication().getUserID());
			} else {
				FacesMessage msg = new FacesMessage();
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				msg.setSummary("That company either does not exist or hasn't been registered yet.");
				FacesContext.getCurrentInstance().addMessage(null, msg);
				return;
			}
		}
		Connection conn = null;
		try {
			conn = ds.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT APP.CLIENTS.CLIENT_ID,APP.CLIENTS.COMPANYNAME,APP.CLIENTS.PARTNER_PROFILE_PAGE,APP.CLIENTS.SHOW_DEALS_ON_PROFILE_PAGE ,(SELECT COUNT(*) FROM APP.DEALS WHERE APP.DEALS.COMPANYID = APP.CLIENTS.CLIENT_ID) AS DEAL_COUNT FROM APP.CLIENTS WHERE client_id = '" + this.currentProfile.getCompanyId() + "'");
			if (rs.next()) {
				this.currentProfile.setCompanyName(rs.getString("COMPANYNAME"));
				this.currentProfile.setProfilePage(rs.getString("PARTNER_PROFILE_PAGE"));
				this.currentProfile.setShowDealsOnPage(rs.getInt("SHOW_DEALS_ON_PROFILE_PAGE") == 1);
				this.currentProfile.setNumDeals(rs.getInt("DEAL_COUNT"));
			} else {
				FacesMessage msg = new FacesMessage();
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				msg.setSummary("That company either does not exist or hasn't been registered yet.");
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
	}

	public String doSaveCompanyProfile() throws SQLException {
		Connection conn = null;
		try {
			conn = ds.getConnection();
			Statement stmt = conn.createStatement();
			String sql = "UPDATE APP.CLIENTS SET "
					+ "companyname = '"
					+ this.currentProfile.getCompanyName()
					+ "', "
					+ "partner_profile_page = '"
					+ this.currentProfile.getProfilePage()
					+ "', "
					+ "show_deals_on_profile_page = "
					+ (this.currentProfile.getShowDealsOnPage() ? "1" : "0")
					+ " WHERE client_id = '"
					+ this.authBean.getAuthentication().getUserID()
					+ "'";
			if (stmt.executeUpdate(sql) == 1) {
				this.authBean.getUserProfile().setCompanyName(this.currentProfile.getCompanyName());
				FacesMessage msg = new FacesMessage();
				msg.setSeverity(FacesMessage.SEVERITY_INFO);
				msg.setSummary("Page saved!");
				FacesContext.getCurrentInstance().addMessage(null, msg);
			} else {
				FacesMessage msg = new FacesMessage();
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				msg.setSummary("Unable to save the page. This error has been reported!");
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		return null;
	}

	public DataModel<PartnerProfile> getPartnerListModel() throws SQLException {
		ArrayList<PartnerProfile> partnerList = new ArrayList<PartnerProfile>();
		Connection conn = null;
		try {
			conn = ds.getConnection();
			Statement stmt = conn.createStatement();
			String sql = "SELECT APP.CLIENTS.CLIENT_ID,APP.CLIENTS.COMPANYNAME,APP.CLIENTS.PARTNER_PROFILE_PAGE,APP.CLIENTS.SHOW_DEALS_ON_PROFILE_PAGE ,(SELECT COUNT(*) FROM APP.DEALS WHERE APP.DEALS.COMPANYID = APP.CLIENTS.CLIENT_ID) AS DEAL_COUNT FROM APP.CLIENTS WHERE APP.CLIENTS.CLIENT_TYPE = " + UserProfileBean.CLIENT_TYPE_PARTNER;
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				PartnerProfile newProfile = new PartnerProfile();
				newProfile.setCompanyId(rs.getString("CLIENT_ID"));
				newProfile.setCompanyName(rs.getString("COMPANYNAME"));
				newProfile.setProfilePage(rs.getString("PARTNER_PROFILE_PAGE"));
				newProfile.setShowDealsOnPage(rs.getInt("SHOW_DEALS_ON_PROFILE_PAGE") == 1);
				newProfile.setNumDeals(rs.getInt("DEAL_COUNT"));
				partnerList.add(newProfile);
			}
		} finally {
			if (conn != null) conn.close();
		}
		return new ArrayDataModel<PartnerProfile>(partnerList.toArray(new PartnerProfile[0]));
	}

	public PartnerProfile getCurrentProfile() {
		return this.currentProfile;
	}

	public void setAuthBean(AuthenticationBean newValue) throws SQLException {
		this.authBean = newValue;
	}

	public void setPartnerId(String newValue) throws SQLException {
		this.currentProfile = new PartnerProfile();
		this.currentProfile.setCompanyId(newValue);
		this.fetchCompanyProfile();
	}

	public String getPartnerId() {
		return this.currentProfile.getCompanyId();
	}

	public void preRenderProfileEditor(ComponentSystemEvent event) {
		try {
			this.fetchCompanyProfile();
		} catch (SQLException ex) {
			ex.printStackTrace(System.err);
			FacesMessage msg = new FacesMessage();
			msg.setSeverity(FacesMessage.SEVERITY_FATAL);
			msg.setSummary("Database Error");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
	}
}
